﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

using Eforcity.Common35;
using Eforcity.Data.Common35;
using Eforcity.EbayApiDb;
using Eforcity.EbayApi.Ebay.TradingApi.Webservice;

namespace Eforcity.EbayApi
{
    public partial class EbayTradingApi : IDisposable
    {
        private const int _RetrySleepTime = 5000; //(5sec)
        private int _ApiMaxRetry = 5;
        private string _APIEndPoint = string.Empty;
        private ConnectionStringSettings _EbayStatConn;
        private EbayCredentialsType _Credentials;


        //For Renew Credential        
        private bool _UseSpecificCredentialId = false;
        private bool _UseSpecificSellerId = false;
        private bool _AllowNonSpecificCredential = false;

        private int _CredentialId = -1;
        private int _SellerId = -1;
        private int _SessionCallLimit = 100;
        private int _SessionCallCount = 0;
        private int _MinmumCallAvali = 0;


        public EbayTradingApi(string apiEndPoint, int apiMaxRetry, int sessionCallLimit, int minCallAvail, ConnectionStringSettings ebayStatConn)
        {
            _EbayStatConn = ebayStatConn;
            _APIEndPoint = apiEndPoint;
            _ApiMaxRetry = apiMaxRetry;
            _SessionCallLimit = sessionCallLimit;
            _UseSpecificSellerId = false;
            _UseSpecificCredentialId = false;
            _AllowNonSpecificCredential = true;
            _MinmumCallAvali = minCallAvail;
            RenewCredentials();
            PreLoadCodeType();
        }
        public EbayTradingApi(string apiEndPoint, int apiMaxRetry, int sessionCallLimit, int sellerId,
            bool allowNonSpecificCredential, int minCallAvail, ConnectionStringSettings ebayStatConn)
        {
            _EbayStatConn = ebayStatConn;
            _APIEndPoint = apiEndPoint;
            _ApiMaxRetry = apiMaxRetry;
            _SessionCallLimit = sessionCallLimit;
            _SellerId = sellerId;
            _UseSpecificSellerId = true;
            _UseSpecificCredentialId = false;
            _AllowNonSpecificCredential = allowNonSpecificCredential;
            _MinmumCallAvali = minCallAvail;
            RenewCredentials();
            PreLoadCodeType();
        }
        public EbayTradingApi(string apiEndPoint, int apiMaxRetry, int sessionCallLimit, int sellerId,
            int credentialId, bool allowNonSpecificCredential, int minCallAvail, ConnectionStringSettings ebayStatConn)
        {
            _EbayStatConn = ebayStatConn;
            _APIEndPoint = apiEndPoint;
            _ApiMaxRetry = apiMaxRetry;
            _SessionCallLimit = sessionCallLimit;
            _SellerId = sellerId;
            _CredentialId = credentialId;
            _UseSpecificSellerId = true;
            _UseSpecificCredentialId = true;
            _AllowNonSpecificCredential = allowNonSpecificCredential;
            _MinmumCallAvali = minCallAvail;
            RenewCredentials();
            PreLoadCodeType();
        }
        public EbayTradingApi(string apiEndPoint, int apiMaxRetry, int sessionCallLimit, int sellerId,
            bool allowNonSpecificCredential, int minCallAvail, bool preloadDisputeCT, ConnectionStringSettings ebayStatConn)
        {
            _EbayStatConn = ebayStatConn;
            _APIEndPoint = apiEndPoint;
            _ApiMaxRetry = apiMaxRetry;
            _SessionCallLimit = sessionCallLimit;
            _SellerId = sellerId;
            _UseSpecificSellerId = true;
            _UseSpecificCredentialId = false;
            _AllowNonSpecificCredential = allowNonSpecificCredential;
            _MinmumCallAvali = minCallAvail;
            RenewCredentials();
            PreLoadCodeType(preloadDisputeCT);
        }

        private void RenewCredentials()
        {
            _Credentials = null;
            //Check _UseSpecificSellerId _UseSpecificCredentialId
            if (_UseSpecificCredentialId)
            {
                _Credentials = EbayCredentialsData.GetEbayCredentials(_SellerId, _CredentialId, false, _MinmumCallAvali, _EbayStatConn);
            }
            else if (_UseSpecificSellerId)
            {
                _Credentials = EbayCredentialsData.GetEbayCredentials(_SellerId, false, _MinmumCallAvali, _EbayStatConn);
            }
            else
            {
                _Credentials = EbayCredentialsData.GetEbayCredentials(false, _MinmumCallAvali, _EbayStatConn);
            }

            //If The Key Allow NonSpecific, Have a 2nd try
            if (_Credentials == null && _AllowNonSpecificCredential)
            {
                _Credentials = EbayCredentialsData.GetEbayCredentials(false, _MinmumCallAvali, _EbayStatConn);
            }

            //See if the key still valid, or any key availabe
            if (_Credentials == null)
            {
                throw new Exception("No Credentials Key Available");
            }
        }
        private void UpdateSessionCallCount()
        {
            _SessionCallCount++;
            if (_SessionCallCount >= _SessionCallLimit)
            {
                RenewCredentials();
                //Reset call count
                _SessionCallCount = 0;
            }
        }
        private void UpdateSessionCallCount(string callname, ref eBayAPIInterfaceService service)
        {
            _SessionCallCount++;
            if (_SessionCallCount >= _SessionCallLimit)
            {
                RenewCredentials();
                service = SetRequesterCredentials(callname);
                //Reset call count
                _SessionCallCount = 0;
            }
        }

        public void Dispose()
        {
            if (_EbayStatConn != null)
            {
                _EbayStatConn = null;
            }
            GC.Collect();
        }

        private eBayAPIInterfaceService SetRequesterCredentials(string callname)
        {
            // Build the request URL 
            StringBuilder requestURLSb = new StringBuilder();
            requestURLSb.Append(_APIEndPoint);
            requestURLSb.AppendFormat("?callname={0}", callname);
            requestURLSb.AppendFormat("&siteid={0}", _Credentials.SiteId);
            requestURLSb.AppendFormat("&appid={0}", _Credentials.AppId);
            requestURLSb.AppendFormat("&version={0}", _Credentials.Version);
            requestURLSb.Append("&routing=default");

            // Create the service 
            eBayAPIInterfaceService service = new eBayAPIInterfaceService();
            // Assign the request URL to the service locator. 
            service.Url = requestURLSb.ToString();
            // Set credentials 
            service.RequesterCredentials = new CustomSecurityHeaderType();
            service.RequesterCredentials.eBayAuthToken = _Credentials.AuthToken;
            service.RequesterCredentials.Credentials = new UserIdPasswordType();
            service.RequesterCredentials.Credentials.AppId = _Credentials.AppId;
            service.RequesterCredentials.Credentials.DevId = _Credentials.DevId;
            service.RequesterCredentials.Credentials.AuthCert = _Credentials.CertId;

            return service;
        }

        //Ebay API Calls
        public ApiAccessRuleType[] GetApiAccessRules()
        {
            string apiName = "GetApiAccessRules";
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            GetApiAccessRulesRequestType request = new GetApiAccessRulesRequestType();
            request.Version = _Credentials.Version.ToString();
            GetApiAccessRulesResponseType response = null;
            int retryCount = 0;
            while (retryCount <= _ApiMaxRetry)
            {
                try
                {
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.GetApiAccessRules(request);
                    if (response == null)
                    {
                        throw new Exception("Response is null.");
                    }
                    break;
                }
                catch (Exception ex)
                {
                    //=========================
                    //RESPONSE ERROR (SYS LEVEL)
                    //=========================
                    EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, string.Empty, ex.Message, _EbayStatConn);
                    //Sleep
                    System.Threading.Thread.Sleep(_RetrySleepTime);
                    retryCount++;
                    //Break  
                    if (retryCount > _ApiMaxRetry)
                    {
                        return null;
                    }
                }
            }
            //=========================
            //RESPONSE ERROR (APP LEVEL)
            //=========================
            if (response.Errors != null)
            {
                EbayErrorStatusEnum errorStatus = EbayErrorStatusEnum.None;
                if (response.Ack == AckCodeType.Warning)
                {
                    errorStatus = EbayErrorStatusEnum.Warning;
                }
                else if (response.Ack == AckCodeType.Failure)
                {
                    errorStatus = EbayErrorStatusEnum.Failure;
                }
                foreach (ErrorType errType in response.Errors)
                {
                    string errMsg = string.Empty;
                    if (errType.SeverityCodeSpecified)
                    {
                        errMsg += errType.SeverityCode.ToString() + ": ";
                    }
                    errMsg += errType.LongMessage;
                    EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.ApiLevel, errorStatus, errType.ErrorCode, errMsg, _EbayStatConn);
                }
            }
            if (response.Ack == AckCodeType.Success || response.Ack == AckCodeType.Warning)
            {
                return response.ApiAccessRule;
            }
            return null;
        }

        public List<EbayListingItemType> GetSellerList(int sellerId, string sellerName, bool isOwner,
            DateTime startTimeFrom, DateTime startTimeTo, bool byEndDate, int entriesPerPage)
        {
            string apiName = "GetSellerList";
            List<EbayListingItemType> ebayListingItemList = new List<EbayListingItemType>();

            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            //Seller Listing Request
            GetSellerListRequestType getSellerRequest = new GetSellerListRequestType();
            getSellerRequest.Version = _Credentials.Version.ToString();

            //We have to get everything is we needed Title
            //DetailLevelCodeType[] dvt = new DetailLevelCodeType[2] { DetailLevelCodeType.ReturnAll, DetailLevelCodeType.ItemReturnAttributes};
            //getSellerRequest.DetailLevel = dvt;
            getSellerRequest.GranularityLevelSpecified = true;
            getSellerRequest.GranularityLevel = GranularityLevelCodeType.Fine;

            if (byEndDate)
            {
                getSellerRequest.EndTimeFromSpecified = true;
                getSellerRequest.EndTimeToSpecified = true;
                getSellerRequest.EndTimeFrom = startTimeFrom;
                getSellerRequest.EndTimeTo = startTimeTo;
            }
            else
            {
                getSellerRequest.StartTimeFromSpecified = true;
                getSellerRequest.StartTimeToSpecified = true;
                getSellerRequest.StartTimeFrom = startTimeFrom;
                getSellerRequest.StartTimeTo = startTimeTo;
            }

            getSellerRequest.IncludeWatchCountSpecified = true;
            getSellerRequest.IncludeWatchCount = true;
            getSellerRequest.Pagination = new PaginationType();
            getSellerRequest.Pagination.PageNumberSpecified = true;
            getSellerRequest.Pagination.EntriesPerPage = entriesPerPage;
            getSellerRequest.Pagination.EntriesPerPageSpecified = true;
            getSellerRequest.UserID = sellerName;

            //Loop the page
            int pageCounter = 1;
            int retryCount = 0;
            bool finished = false;
            string plPattern = @"\?[\s\S]*pl=(\d+)";
            string imageUrl = null;
            do
            {
                getSellerRequest.Pagination.PageNumber = pageCounter;
                GetSellerListResponseType response;
                try
                {
                    //Must have a count update before anycall
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.GetSellerList(getSellerRequest);
                }
                catch (Exception ex)
                {
                    //=========================
                    //RESPONSE ERROR (SYS LEVEL)
                    //=========================
                    EbayErrorData.InsertErrorGetSellerList(sellerId, startTimeFrom, startTimeTo, entriesPerPage,
                            pageCounter, EbayErrorTypeEnum.SysLevel, -1, ex.Message, _EbayStatConn);

                    //Sleep
                    System.Threading.Thread.Sleep(_RetrySleepTime);//5000

                    //Retry or Break                        
                    if (retryCount < _ApiMaxRetry)
                    {
                        retryCount++;
                        continue;
                    }
                    else
                    {
                        return null;
                    }
                }

                //=========================
                //RESPONSE ERROR (APP LEVEL)
                //=========================
                if (response.Errors != null)
                {
                    foreach (ErrorType errType in response.Errors)
                    {
                        EbayErrorData.InsertErrorGetSellerList(sellerId, startTimeFrom, startTimeTo, entriesPerPage,
                            pageCounter, EbayErrorTypeEnum.ApiLevel, ConvertUtility.ToInt(errType.ErrorCode), errType.LongMessage, _EbayStatConn);

                        //Seller Name Not Found = 21
                        if (errType.ErrorCode == "21")
                        {
                            EbaySellerData.UpdateSellerStatus(sellerId, false, true, _EbayStatConn);
                        }
                    }
                    //any error occur in a process lot means Whole lot fail, and have to retry      
                    return null;
                }
                if (response.ItemArray == null)
                {
                    //Shall be Error
                    return null;
                }

                //================
                //PROCESS RESPONSE
                //================
                bool topRatedSeller = false;
                if (response.Seller != null)
                {
                    if (response.Seller.SellerInfo != null)
                    {
                        if (response.Seller.SellerInfo.TopRatedSellerSpecified)
                        {
                            topRatedSeller = response.Seller.SellerInfo.TopRatedSeller;
                        }
                    }
                }
                if (response.ItemArray.Length != 0)
                {
                    //Preform the update here
                    foreach (ItemType itemType in response.ItemArray)
                    {
                        EbayListingItemType listingItem = new EbayListingItemType();

                        listingItem.ItemId = ConvertUtility.ToInt64(itemType.ItemID);
                        listingItem.SKU = ConvertUtility.Trim(itemType.SKU);
                        listingItem.SellerID = sellerId;
                        listingItem.TopRatedSeller = topRatedSeller;

                        listingItem.StartDateTime = itemType.ListingDetails.StartTime;
                        listingItem.EndDateTime = itemType.ListingDetails.EndTime;

                        listingItem.ListingDurationId = GetListingDurationId(itemType.ListingDuration);
                        listingItem.Title = ConvertUtility.Trim(itemType.Title);
                        listingItem.SubTitle = ConvertUtility.Trim(itemType.SubTitle);
                        listingItem.AuctionSite = GetSiteId(itemType.Site.ToString());

                        listingItem.Currency = GetCurrencyId(itemType.Currency.ToString());
                        listingItem.StartPrice = ConvertUtility.ToDecimal(itemType.StartPrice.Value);
                        listingItem.ConvertedStartPrice = ConvertUtility.ToDecimal(itemType.ListingDetails.ConvertedStartPrice.Value);
                        listingItem.BuyItNowPrice = ConvertUtility.ToDecimal(itemType.BuyItNowPrice.Value);
                        listingItem.ConvertedBuyItNowPrice = ConvertUtility.ToDecimal(itemType.ListingDetails.ConvertedBuyItNowPrice.Value);

                        listingItem.QtyLaunch = itemType.Quantity;

                        if (isOwner)
                        {
                            if (itemType.PictureDetails != null)
                            {
                                imageUrl = itemType.PictureDetails.GalleryURL;
                            }
                            if (!string.IsNullOrEmpty(imageUrl))
                            {
                                if (Regex.IsMatch(imageUrl, plPattern))
                                {
                                    listingItem.ProductLine = ConvertUtility.ToInt(Regex.Match(imageUrl, plPattern).Groups[1].Value);
                                }
                            }
                        }
                        listingItem.ProductLine = listingItem.ProductLine <= 0 ? 99 : listingItem.ProductLine;

                        if (itemType.SellingStatus != null)
                        {
                            listingItem.QtySold = itemType.SellingStatus.QuantitySold;
                            if (itemType.SellingStatus.ListingStatusSpecified)
                            {
                                if (itemType.SellingStatus.ListingStatus == ListingStatusCodeType.Ended
                                    || itemType.SellingStatus.ListingStatus == ListingStatusCodeType.Completed)
                                {
                                    //Listing has ended
                                    if (listingItem.QtySold == 0)
                                    {
                                        listingItem.ListingStatus = EbayListingStatusEnum.Completed;
                                    }
                                    else
                                    {
                                        listingItem.ListingStatus = EbayListingStatusEnum.Ended;
                                    }
                                    listingItem.FinalEndDateTime = itemType.ListingDetails.EndTime;
                                }
                            }
                        }
                        else
                        {
                            //response.Item.SellingStatus should be Always return
                            listingItem.QtySold = 0;
                            //If EndDate < eBay processed the request Time -> Endend
                            if (listingItem.EndDateTime < response.Timestamp)
                            {
                                //Listing has ended
                                listingItem.ListingStatus = EbayListingStatusEnum.Completed;
                                listingItem.FinalEndDateTime = itemType.ListingDetails.EndTime;
                            }
                        }

                        listingItem.ListingType = GetListingTypeId(itemType.ListingType.ToString());
                        if (itemType.PictureDetails != null)
                        {
                            if (itemType.PictureDetails.GalleryTypeSpecified)
                            {
                                listingItem.GalleryType = GetGalleryTypeId(itemType.PictureDetails.GalleryType.ToString());
                            }
                        }
                        listingItem.CategoryId = ConvertUtility.ToInt(itemType.PrimaryCategory.CategoryID);


                        #region ShippingDetails
                        if (itemType.ShippingDetails.ShippingServiceOptions != null)
                        {
                            foreach (ShippingServiceOptionsType shippingServiceOptions in itemType.ShippingDetails.ShippingServiceOptions)
                            {
                                EbayShippingServiceType eBayShipping = new EbayShippingServiceType();
                                if (shippingServiceOptions.ShippingService != null)
                                {
                                    eBayShipping.ShippingServiceId = GetShippingServiceId(shippingServiceOptions.ShippingService, shippingServiceOptions.ExpeditedService);
                                }
                                else
                                {
                                    eBayShipping.ShippingServiceId = GetShippingServiceId("NA", shippingServiceOptions.ExpeditedService);
                                }
                                if (shippingServiceOptions.ShippingServiceCost != null)
                                {
                                    eBayShipping.ShippingServiceCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value);
                                    eBayShipping.ShippingServiceCurrency = GetCurrencyId(shippingServiceOptions.ShippingServiceCost.currencyID.ToString());

                                    #region GetStandardShipping
                                    if (shippingServiceOptions.ShippingService.ToLower().Contains("standard")
                                        && eBayShipping.ShippingServiceCurrency == listingItem.Currency)
                                    {
                                        //Standard Only
                                        if (listingItem.ShippingServiceCost == -1 ||
                                            (listingItem.ShippingServiceCost != -1 &&
                                            ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value)
                                            < listingItem.ShippingServiceCost))
                                        {
                                            listingItem.ShippingServiceCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value);
                                            //ByEric
                                            listingItem.ShippingServiceId = GetShippingServiceId(shippingServiceOptions.ShippingService, shippingServiceOptions.ExpeditedService);

                                            if (shippingServiceOptions.ShippingServiceAdditionalCost != null)
                                            {
                                                listingItem.ShippingAdditionCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceAdditionalCost.Value);
                                            }
                                            else
                                            {
                                                listingItem.ShippingAdditionCost = 0;
                                            }

                                            if (shippingServiceOptions.ShippingSurcharge != null)
                                            {
                                                listingItem.ShippingSurcharge = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingSurcharge.Value);
                                            }
                                            else
                                            {
                                                listingItem.ShippingSurcharge = 0;
                                            }
                                        }
                                    }
                                    #endregion
                                }
                                if (shippingServiceOptions.ShippingServiceAdditionalCost != null)
                                {
                                    eBayShipping.ShippingServiceAdditionalCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceAdditionalCost.Value);
                                }
                                if (shippingServiceOptions.ShippingSurcharge != null)
                                {
                                    eBayShipping.ShippingSurcharge = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingSurcharge.Value);
                                }

                                //Add by Joseph 20100519
                                eBayShipping.ExpeditedService = shippingServiceOptions.ExpeditedService;

                                listingItem.ShippingServiceList.Add(eBayShipping);
                            }
                            #region If no StandardShipping, use the minimum
                            if (listingItem.ShippingServiceCost == -1)
                            {
                                //NO Standard In the List, Pick the cheapest one if any
                                foreach (ShippingServiceOptionsType shippingServiceOptions in itemType.ShippingDetails.ShippingServiceOptions)
                                {
                                    if (shippingServiceOptions.ShippingServiceCost != null)
                                    {
                                        if (listingItem.ShippingServiceCost == -1 || (
                                            ConvertUtility.ToDecimal
                                            (shippingServiceOptions.ShippingServiceCost.Value)
                                            < listingItem.ShippingServiceCost))
                                        {
                                            listingItem.ShippingServiceCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value);
                                            //ByEric
                                            listingItem.ShippingServiceId = GetShippingServiceId(shippingServiceOptions.ShippingService, shippingServiceOptions.ExpeditedService);

                                            if (shippingServiceOptions.ShippingServiceAdditionalCost != null)
                                            {
                                                listingItem.ShippingAdditionCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceAdditionalCost.Value);
                                            }
                                            else
                                            {
                                                listingItem.ShippingAdditionCost = 0;
                                            }
                                            if (shippingServiceOptions.ShippingSurcharge != null)
                                            {
                                                listingItem.ShippingSurcharge = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingSurcharge.Value);
                                            }
                                            else
                                            {
                                                listingItem.ShippingSurcharge = 0;
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        #region If no valid shipping free, set them to zero
                        if (listingItem.ShippingServiceCost == -1)
                        {
                            //ByEric
                            listingItem.ShippingServiceId = 13;
                            listingItem.ShippingServiceCost = 0;
                            listingItem.ShippingAdditionCost = 0;
                            listingItem.ShippingSurcharge = 0;
                        }
                        #endregion
                        #endregion

                        #region ListingEnhancement
                        if (itemType.ListingEnhancement != null)
                        {
                            foreach (ListingEnhancementsCodeType listingEnhancement in itemType.ListingEnhancement)
                            {
                                listingItem.ListingEnhancementType.Add(GetListingEnhancementCodeTypeId(listingEnhancement.ToString()));
                            }
                        }
                        #endregion

                        listingItem.FeaturedType = EbayListingData.GetFeaturedType(listingItem.AuctionSite, listingItem.TopRatedSeller, listingItem.GalleryType, listingItem.ListingEnhancementType);

                        ebayListingItemList.Add(listingItem);
                    }

                    pageCounter++;
                    retryCount = 0;

                    if (pageCounter > response.PaginationResult.TotalNumberOfPages)
                    {
                        //Reach last Page 
                        finished = true;
                    }
                }
                else
                {
                    //Response Contains 0 item
                    finished = true;
                }
            }
            while (!finished);

            return ebayListingItemList;
        }

        public int GetSellerListCount(int sellerId, DateTime startTimeFrom, DateTime startTimeTo)
        {
            int listingCount = -1;

            string apiName = "GetSellerList";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            //Seller Listing Request
            GetSellerListRequestType getSellerRequest = new GetSellerListRequestType();
            getSellerRequest.Version = _Credentials.Version.ToString();

            getSellerRequest.GranularityLevelSpecified = true;
            getSellerRequest.GranularityLevel = GranularityLevelCodeType.Coarse;
            getSellerRequest.StartTimeFromSpecified = true;
            getSellerRequest.StartTimeToSpecified = true;
            getSellerRequest.StartTimeFrom = startTimeFrom;
            getSellerRequest.StartTimeTo = startTimeTo;
            getSellerRequest.IncludeWatchCountSpecified = true;
            getSellerRequest.IncludeWatchCount = true;
            getSellerRequest.Pagination = new PaginationType();
            getSellerRequest.Pagination.PageNumberSpecified = true;
            getSellerRequest.Pagination.EntriesPerPage = 1;
            getSellerRequest.Pagination.EntriesPerPageSpecified = true;
            getSellerRequest.UserID = EbaySellerData.GetEbaySellerName(sellerId, _EbayStatConn); //Get the ebaySellerId Here

            int retryCount = 0;
            bool finished = false;
            do
            {
                getSellerRequest.Pagination.PageNumber = 1;
                GetSellerListResponseType response;
                try
                {
                    //Must have a count update before anycall
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.GetSellerList(getSellerRequest);
                }
                catch (Exception ex)
                {
                    //=========================
                    //RESPONSE ERROR (SYS LEVEL)
                    //=========================
                    EbayErrorData.InsertErrorGetSellerList(sellerId, startTimeFrom, startTimeTo, 1,
                            1, EbayErrorTypeEnum.SysLevel, -1, ex.Message, _EbayStatConn);

                    //Sleep
                    System.Threading.Thread.Sleep(_RetrySleepTime);//5000

                    //Retry or Break                        
                    if (retryCount < _ApiMaxRetry)
                    {
                        retryCount++;
                        continue;
                    }
                    else
                    {
                        return -1;
                    }
                }

                //=========================
                //RESPONSE ERROR (APP LEVEL)
                //=========================
                if (response.Errors != null)
                {
                    foreach (ErrorType errType in response.Errors)
                    {
                        EbayErrorData.InsertErrorGetSellerList(sellerId, startTimeFrom, startTimeTo, 1,
                            1, EbayErrorTypeEnum.ApiLevel, ConvertUtility.ToInt(errType.ErrorCode), errType.LongMessage, _EbayStatConn);

                        //Seller Name Not Found = 21
                        if (errType.ErrorCode == "21")
                        {
                            EbaySellerData.UpdateSellerStatus(sellerId, false, true, _EbayStatConn);
                        }
                    }
                    //any error occur in a process lot means Whole lot fail, and have to retry      
                    //Retry or Break                        
                    if (retryCount < _ApiMaxRetry)
                    {
                        retryCount++;
                        continue;
                    }
                    else
                    {
                        return -1;
                    }
                }
                else
                {
                    listingCount = response.PaginationResult.TotalNumberOfEntries;
                    finished = true;
                }
            }
            while (!finished);

            return listingCount;
        }

        public int GetSellerListCount(int sellerId, DateTime startTimeFrom, DateTime startTimeTo, out int retryCount)//add out parameter  -->retryCount
        {
            int listingCount = -1;

            string apiName = "GetSellerList";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            //Seller Listing Request
            GetSellerListRequestType getSellerRequest = new GetSellerListRequestType();
            getSellerRequest.Version = _Credentials.Version.ToString();

            getSellerRequest.GranularityLevelSpecified = true;
            getSellerRequest.GranularityLevel = GranularityLevelCodeType.Coarse;
            getSellerRequest.StartTimeFromSpecified = true;
            getSellerRequest.StartTimeToSpecified = true;
            getSellerRequest.StartTimeFrom = startTimeFrom;
            getSellerRequest.StartTimeTo = startTimeTo;
            getSellerRequest.IncludeWatchCountSpecified = true;
            getSellerRequest.IncludeWatchCount = true;
            getSellerRequest.Pagination = new PaginationType();
            getSellerRequest.Pagination.PageNumberSpecified = true;
            getSellerRequest.Pagination.EntriesPerPage = 1;
            getSellerRequest.Pagination.EntriesPerPageSpecified = true;
            getSellerRequest.UserID = EbaySellerData.GetEbaySellerName(sellerId, _EbayStatConn); //Get the ebaySellerId Here

            retryCount = 0;
            bool finished = false;
            do
            {
                getSellerRequest.Pagination.PageNumber = 1;
                GetSellerListResponseType response;
                try
                {
                    //Must have a count update before anycall
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.GetSellerList(getSellerRequest);
                }
                catch (Exception ex)
                {
                    //=========================
                    //RESPONSE ERROR (SYS LEVEL)
                    //=========================
                    EbayErrorData.InsertErrorGetSellerList(sellerId, startTimeFrom, startTimeTo, 1,
                            1, EbayErrorTypeEnum.SysLevel, -1, ex.Message, _EbayStatConn);

                    //Sleep
                    System.Threading.Thread.Sleep(_RetrySleepTime);//5000

                    //Retry or Break                        
                    if (retryCount < _ApiMaxRetry)
                    {
                        retryCount++;
                        continue;
                    }
                    else
                    {
                        return -1;
                    }
                }

                //=========================
                //RESPONSE ERROR (APP LEVEL)
                //=========================
                if (response.Errors != null)
                {
                    foreach (ErrorType errType in response.Errors)
                    {
                        EbayErrorData.InsertErrorGetSellerList(sellerId, startTimeFrom, startTimeTo, 1,
                            1, EbayErrorTypeEnum.ApiLevel, ConvertUtility.ToInt(errType.ErrorCode), errType.LongMessage, _EbayStatConn);

                        //Seller Name Not Found = 21
                        if (errType.ErrorCode == "21")
                        {
                            EbaySellerData.UpdateSellerStatus(sellerId, false, true, _EbayStatConn);
                        }
                    }
                    //any error occur in a process lot means Whole lot fail, and have to retry      
                    //Retry or Break                        
                    if (retryCount < _ApiMaxRetry)
                    {
                        retryCount++;
                        continue;
                    }
                    else
                    {
                        return -1;
                    }
                }
                else
                {
                    listingCount = response.PaginationResult.TotalNumberOfEntries;
                    finished = true;
                }
            }
            while (!finished);

            return listingCount;
        }

        public ApiErrorType EndItem(long itemId, int sellerId, EndReasonCodeType endingReason)
        {
            string apiName = "EndItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            EndItemRequestType endItemRequest = new EndItemRequestType();
            endItemRequest.Version = _Credentials.Version.ToString();
            endItemRequest.ItemID = ConvertUtility.Trim(itemId);


            endItemRequest.EndingReasonSpecified = true;
            endItemRequest.EndingReason = endingReason;

            EndItemResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount();
                response = service.EndItem(endItemRequest);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorEndItem(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);

                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                //Break  
                return ApiErrorType.SystemError;
            }

            //=========================
            //RESPONSE ERROR (APP LEVEL)
            //=========================
            if (response.Errors != null)
            {
                foreach (ErrorType errType in response.Errors)
                {
                    EbayErrorData.InsertErrorEndItem(itemId, EbayErrorTypeEnum.ApiLevel, errType.LongMessage, _EbayStatConn);
                }
                return ApiErrorType.ApplicationError;
            }


            //Revise Success
            return ApiErrorType.NoError;
        }

        public void GetCategories()
        {
            Dictionary<int, string> siteDict = new Dictionary<int, string>();
            siteDict.Add(0, "US");
            siteDict.Add(3, "UK");
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("SiteName");
            dt.Columns.Add("AutoPayEnabled");
            dt.Columns.Add("B2BVATEnabled");
            dt.Columns.Add("BestOfferEnabled");
            dt.Columns.Add("CatalogEnabled");
            dt.Columns.Add("CategoryID");
            dt.Columns.Add("CategoryLevel");
            dt.Columns.Add("CategoryName");
            dt.Columns.Add("CategoryParentID");
            dt.Columns.Add("CategoryParentName");
            dt.Columns.Add("Expired");
            dt.Columns.Add("IntlAutosFixedCat");
            dt.Columns.Add("Keywords");
            dt.Columns.Add("LeafCategory");
            dt.Columns.Add("LSD");
            dt.Columns.Add("NumOfItems");
            dt.Columns.Add("ORPA");
            dt.Columns.Add("ORRA");
            dt.Columns.Add("ProductSearchPageAvailable");
            dt.Columns.Add("SellerGuaranteeEligible");
            dt.Columns.Add("Virtual");

            string apiName = "GetCategories";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            foreach (int siteId in siteDict.Keys)
            {
                GetCategoriesRequestType request = new GetCategoriesRequestType();
                request.DetailLevel = new DetailLevelCodeType[] { DetailLevelCodeType.ReturnAll };
                request.Version = _Credentials.Version.ToString();
                //request.ViewAllNodesSpecified = true;
                //request.ViewAllNodes = true;
                /*request.LevelLimitSpecified = true;
                request.LevelLimit = 1;*/
                request.CategorySiteID = siteId.ToString();
                //request.CategoryParent = new string[] { "",""};

                GetCategoriesResponseType response;
                try
                {
                    //Must have a count update before anycall
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.GetCategories(request);
                }
                catch (Exception ex)
                {
                    //=========================
                    //RESPONSE ERROR (SYS LEVEL)
                    //=========================
                    throw ex;
                }
                if (response != null && response.CategoryArray != null)
                {
                    foreach (CategoryType cat in response.CategoryArray)
                    {
                        System.Data.DataRow dr = dt.NewRow();
                        dr["SiteName"] = siteDict[siteId];
                        dr["AutoPayEnabled"] = cat.AutoPayEnabled;
                        dr["B2BVATEnabled"] = cat.B2BVATEnabled;
                        dr["BestOfferEnabled"] = cat.BestOfferEnabled;
                        dr["CatalogEnabled"] = cat.CatalogEnabled;
                        dr["CategoryID"] = cat.CategoryID;
                        dr["CategoryLevel"] = cat.CategoryLevel;
                        dr["CategoryName"] = cat.CategoryName;
                        dr["CategoryParentID"] = string.Join(",", cat.CategoryParentID);
                        dr["CategoryParentName"] = cat.CategoryParentName != null ? string.Join(",", cat.CategoryParentName) : "";
                        dr["Expired"] = cat.Expired;
                        dr["IntlAutosFixedCat"] = cat.IntlAutosFixedCat;
                        dr["Keywords"] = cat.Keywords;
                        dr["LeafCategory"] = cat.LeafCategory;
                        dr["LSD"] = cat.LSD;
                        dr["NumOfItems"] = cat.NumOfItems;
                        dr["ORPA"] = cat.ORPA;
                        dr["ORRA"] = cat.ORRA;
                        dr["ProductSearchPageAvailable"] = cat.ProductSearchPageAvailable;
                        dr["SellerGuaranteeEligible"] = cat.SellerGuaranteeEligible;
                        dr["Virtual"] = cat.Virtual;

                        dt.Rows.Add(dr);
                    }
                }
            }
            GeneralDbUtility.OutputDataTableAsExcel(dt, "cat.xls");
        }

        public List<EbayTransactionType> GetItemTransactionsList(long itemId, long transactionId, DateTime startDate, int entriesPerPage, Action<int, string> trace)
        {
            string apiName = "GetItemTransactions";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            List<EbayTransactionType> ebayTranList = new List<EbayTransactionType>();

            GetItemTransactionsRequestType request = new GetItemTransactionsRequestType();
            request.Version = _Credentials.Version.ToString();
            request.DetailLevel = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnAll };
            request.Pagination = new PaginationType();
            request.Pagination.EntriesPerPageSpecified = true;
            request.Pagination.EntriesPerPage = entriesPerPage;
            request.Pagination.PageNumberSpecified = true;
            if (transactionId >= 0)
            {
                request.TransactionID = transactionId.ToString();
            }
            else
            {
                request.ModTimeFromSpecified = true;
                request.ModTimeToSpecified = true;
            }
            request.ItemID = itemId.ToString();
            GetItemTransactionsResponseType response = null;
            List<string> transIdList = new List<string>();
            //Loop the ModTime
            const int modDayRange = 29;//max ModTime Day Ranage is 30 days

            DateTime modTimeFrom = DateTimeUtility.ToBeginingOfTheDay(startDate);
            bool modTimeFinished = false;
            do
            {
                request.ModTimeFrom = modTimeFrom.AddMinutes(-1);
                request.ModTimeTo = modTimeFrom.AddDays(modDayRange).AddMinutes(1);

                trace(0, String.Format("  Processing from  {0}  to  {1}..."
                    , request.ModTimeFrom.ToString("MM/dd/yy  HH:mm")
                    , request.ModTimeTo.ToString("MM/dd/yy  HH:mm")));

                //Loop the page
                int pageCounter = 1;
                bool finished = false;
                do
                {
                    request.Pagination.PageNumber = pageCounter;
                    int retryCount = 0;
                    while (retryCount <= _ApiMaxRetry)
                    {
                        try
                        {
                            //Must have a count update before anycall
                            UpdateSessionCallCount(apiName, ref service);
                            response = service.GetItemTransactions(request);
                            break;
                        }
                        catch (Exception ex)
                        {
                            //=========================
                            //RESPONSE ERROR (SYS LEVEL)
                            //=========================
                            EbayErrorData.InsertErrorGetItemTransactions(itemId,
                                request.ModTimeFrom, request.ModTimeTo, entriesPerPage,
                                pageCounter, EbayErrorTypeEnum.SysLevel, -1, ex.Message,
                                _EbayStatConn);

                            //Sleep
                            System.Threading.Thread.Sleep(_RetrySleepTime);
                            retryCount++;
                            //Break  
                            if (retryCount > _ApiMaxRetry)
                            {
                                break;
                            }
                        }
                    }
                    if (response == null)
                    {
                        //Return null if any page cannot response for each item.
                        return null;
                    }

                    if (response.PaginationResult != null)
                    {
                        trace(0, String.Format("    page {0} of {1}", pageCounter, response.PaginationResult.TotalNumberOfPages));
                    }

                    //=========================
                    //RESPONSE ERROR (APP LEVEL)
                    //=========================
                    if (response.Errors != null)
                    {
                        foreach (ErrorType errType in response.Errors)
                        {
                            EbayErrorData.InsertErrorGetItemTransactions(itemId,
                                 request.ModTimeFrom, request.ModTimeTo, entriesPerPage,
                                 pageCounter, EbayErrorTypeEnum.ApiLevel,
                                 ConvertUtility.ToInt(errType.ErrorCode),
                                 errType.LongMessage, _EbayStatConn);
                        }
                        //Return null if any page cannot response for each item.
                        return null;
                    }

                    if (response.TransactionArray != null && response.TransactionArray.Length > 0)
                    {
                        foreach (TransactionType trans in response.TransactionArray)
                        {
                            if (transIdList.Contains(trans.TransactionID))
                            {
                                continue;
                            }
                            else
                            {
                                transIdList.Add(trans.TransactionID);
                            }
                            EbayTransactionType transDbType = new EbayTransactionType();
                            transDbType.ItemId = itemId;
                            transDbType.TransactionID = ConvertUtility.ToInt64(trans.TransactionID);
                            transDbType.EbayUserId = trans.Buyer.UserID;
                            if (trans.Status != null)
                            {
                                if (!_CompleteStatusCodeTypeDict.ContainsKey(trans.Status.CompleteStatus.ToString()))
                                {
                                    EbayCodeTypeData.InsertCompleteStatusCodeType(Convert.ToByte(trans.Status.CompleteStatus.ToString("D")), trans.Status.CompleteStatus.ToString(), _EbayStatConn);
                                    //Renew 
                                    _CompleteStatusCodeTypeDict = EbayCodeTypeData.GetCompleteStatusCodeTypeDict(_EbayStatConn);
                                }
                                transDbType.CompleteStatusId = _CompleteStatusCodeTypeDict[trans.Status.CompleteStatus.ToString()];
                                if (!_CheckOutStatusCodeTypeDict.ContainsKey(trans.Status.CheckoutStatus.ToString()))
                                {
                                    //Renew 
                                    EbayCodeTypeData.InsertCheckOutStatusCodeType(Convert.ToByte(trans.Status.CheckoutStatus.ToString("D")), trans.Status.CheckoutStatus.ToString(), _EbayStatConn);
                                    _CheckOutStatusCodeTypeDict = EbayCodeTypeData.GetCheckOutStatusCodeTypeDict(_EbayStatConn);
                                }
                                transDbType.CheckoutStatusId = _CheckOutStatusCodeTypeDict[trans.Status.CheckoutStatus.ToString()];
                                if (!_PaymentStatucCodeTypeDict.ContainsKey(trans.Status.eBayPaymentStatus.ToString()))
                                {
                                    //Renew 
                                    EbayCodeTypeData.InsertPaymentStatusCodeType(Convert.ToByte(trans.Status.eBayPaymentStatus.ToString("D")), trans.Status.eBayPaymentStatus.ToString(), _EbayStatConn);
                                    _PaymentStatucCodeTypeDict = EbayCodeTypeData.GetPaymentStatusCodeTypeDict(_EbayStatConn);
                                }
                                transDbType.PaymentStatusId = _PaymentStatucCodeTypeDict[trans.Status.eBayPaymentStatus.ToString()];

                                if (trans.Status.LastTimeModified != null)
                                {
                                    transDbType.LastTimeModified = trans.Status.LastTimeModified;
                                }
                            }
                            transDbType.CreatedDate = trans.CreatedDate;
                            transDbType.QuantityPurchased = trans.QuantityPurchased;
                            if (!string.IsNullOrEmpty(trans.Buyer.Email))
                            {
                                transDbType.BuyerEmail = trans.Buyer.Email;
                            }
                            ebayTranList.Add(transDbType);
                        }//end foreach

                        pageCounter++;
                        if (pageCounter > response.PaginationResult.TotalNumberOfPages)
                        {
                            //Reach last Page 
                            finished = true;
                        }
                    }
                    else
                    {
                        //No Bidder for this range of modTime
                        //pageCounter should be 1
                        if (pageCounter != 1)
                        {
                            EbayErrorData.InsertErrorGetItemTransactions(itemId,
                                 request.ModTimeFrom, request.ModTimeTo, entriesPerPage,
                                 pageCounter, EbayErrorTypeEnum.ApiLevel, -1,
                                 "Nothing in response.TransactionArray.", _EbayStatConn);
                            return null;
                        }
                        finished = true;
                    }
                }//end do (page loop)
                while (!finished);
                if (request.ModTimeTo >= DateTime.Now.ToUniversalTime())
                {
                    modTimeFinished = true;
                }
                modTimeFrom = modTimeFrom.AddDays(modDayRange);
            }//end do (modTime loop)
            while (!modTimeFinished);
            return ebayTranList;
        }

        public ApiErrorType AddDispute(long itemId, long transactionId,
            string disputeReason, string disputeExplanation,
            out long disputeId)
        {
            string apiName = "AddDispute";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            AddDisputeRequestType request = new AddDisputeRequestType();
            request.Version = _Credentials.Version.ToString();
            request.ItemID = itemId.ToString();
            request.TransactionID = transactionId.ToString();
            request.DisputeReasonSpecified = true;
            request.DisputeReason = (DisputeReasonCodeType)Enum.Parse(typeof(DisputeReasonCodeType), disputeReason);
            if (request.DisputeReason.ToString().ToLower() != disputeReason.ToLower())
            {
                throw new Exception("Invalid disputeReason.");
            }
            //request.DisputeReason = DisputeReasonCodeType.TransactionMutuallyCanceled;
            request.DisputeExplanationSpecified = true;
            request.DisputeExplanation = (DisputeExplanationCodeType)Enum.Parse(typeof(DisputeExplanationCodeType), disputeExplanation);
            if (request.DisputeExplanation.ToString().ToLower() != disputeExplanation.ToLower())
            {
                throw new Exception("Invalid disputeExplanation.");
            }
            //request.DisputeExplanation = DisputeExplanationCodeType.BuyerNoLongerWantsItem;

            disputeId = 0;
            AddDisputeResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount();
                response = service.AddDispute(request);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorAddDispute(itemId, transactionId, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, "-1", ex.Message, _EbayStatConn);

                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                //Break  
                return ApiErrorType.SystemError;
            }

            //=========================
            //RESPONSE ERROR (APP LEVEL)
            //=========================
            if (response.Errors != null)
            {
                EbayErrorStatusEnum errStatus = EbayErrorStatusEnum.None;
                if (response.Ack == AckCodeType.Warning)
                {
                    errStatus = EbayErrorStatusEnum.Warning;
                }
                else if (response.Ack != AckCodeType.Success)
                {
                    errStatus = EbayErrorStatusEnum.Failure;
                }
                foreach (ErrorType errType in response.Errors)
                {
                    EbayErrorData.InsertErrorAddDispute(itemId, transactionId, EbayErrorTypeEnum.ApiLevel, errStatus, errType.ErrorCode, errType.LongMessage, _EbayStatConn);
                }
                if (response.Ack != AckCodeType.Success && response.Ack != AckCodeType.Warning)
                {
                    return ApiErrorType.ApplicationError;
                }
            }
            disputeId = ConvertUtility.ToInt64(response.DisputeID, -1);
            if (disputeId <= 0)
            {
                EbayErrorData.InsertErrorAddDispute(itemId, transactionId, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, "-1", "disputeId <= 0. Response.DisputeId:" + response.DisputeID, _EbayStatConn);
            }

            //Revise Success
            return ApiErrorType.NoError;
        }

        public EbayDisputeType GetDispute(long disputeId)
        {
            string apiName = "GetDispute";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetDisputeRequestType request = new GetDisputeRequestType();
            request.Version = _Credentials.Version.ToString();
            request.DisputeID = disputeId.ToString();

            GetDisputeResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount();
                response = service.GetDispute(request);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                //Break  
                throw new Exception(ex.Message);
            }

            //=========================
            //RESPONSE ERROR (APP LEVEL)
            //=========================
            if (response.Errors != null)
            {
                EbayErrorStatusEnum errStatus = EbayErrorStatusEnum.None;
                if (response.Ack == AckCodeType.Warning)
                {
                    errStatus = EbayErrorStatusEnum.Warning;
                }
                else if (response.Ack != AckCodeType.Success)
                {
                    errStatus = EbayErrorStatusEnum.Failure;
                }
                string errMsg = errStatus.ToString() + ":";
                foreach (ErrorType errType in response.Errors)
                {
                    errMsg += errType.LongMessage + "\r\n";
                }
                throw new Exception(errMsg);
            }
            if (response.Dispute == null)
            {
                throw new Exception("response.Dispute is null");
            }
            EbayDisputeType disputeType = new EbayDisputeType();
            disputeType.DisputeReasonId = ConvertUtility.ToInt(GetDisputeReasonId(response.Dispute.DisputeReason.ToString()));
            disputeType.DisputeExplanationId = ConvertUtility.ToInt(GetDisputeExplanationId(response.Dispute.DisputeExplanation.ToString()));
            disputeType.DisputeCreditEligibilityId = ConvertUtility.ToInt(GetDisputeCreditEligibilityId(response.Dispute.DisputeCreditEligibility.ToString()));
            disputeType.DisputeRecordTypeId = ConvertUtility.ToInt(GetDisputeRecordTypeId(response.Dispute.DisputeRecordType.ToString()));
            disputeType.DisputeStateId = ConvertUtility.ToInt(GetDisputeStateId(response.Dispute.DisputeState.ToString()));
            disputeType.DisputeStatusId = ConvertUtility.ToInt(GetDisputeStatusId(response.Dispute.DisputeStatus.ToString()));
            disputeType.DisputeCreateTime = response.Dispute.DisputeCreatedTime;
            disputeType.DisputeModifiedTime = response.Dispute.DisputeModifiedTime;
            if (response.Dispute.DisputeMessage != null && response.Dispute.DisputeMessage.Length > 0)
            {
                disputeType.DisputeMessages = new List<EbayDisputeMessageType>();
                foreach (DisputeMessageType responseDisputeMessageType in response.Dispute.DisputeMessage)
                {
                    EbayDisputeMessageType disputeMessageType = new EbayDisputeMessageType();
                    disputeMessageType.DisputeId = disputeId;
                    disputeMessageType.MessageId = ConvertUtility.ToInt64(responseDisputeMessageType.MessageID);
                    disputeMessageType.DisputeMessageSourceId = ConvertUtility.ToInt(GetDisputeMessageSourceId(responseDisputeMessageType.MessageSource.ToString()));
                    disputeMessageType.MessageCreationTime = responseDisputeMessageType.MessageCreationTime;
                    disputeMessageType.MessageText = responseDisputeMessageType.MessageText;
                    disputeType.DisputeMessages.Add(disputeMessageType);
                }//end foreach
            }//end if

            //ProcessStatusDefine
            if (response.Dispute.DisputeState == DisputeStateCodeType.Closed)
            {
                disputeType.ProcessStatus = DisputeProcessStatusEnum.DisputeCaseClosed;
            }

            return disputeType;
        }

        public void GetUserDisputes()
        {
            string apiName = "GetUserDisputes";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetUserDisputesRequestType request = new GetUserDisputesRequestType();
            request.Version = _Credentials.Version.ToString();
            request.DisputeSortType = DisputeSortTypeCodeType.DisputeCreatedTimeAscending;
            request.DisputeSortTypeSpecified = true;
            request.ModTimeFrom = DateTime.Today.AddDays(-2).Date.ToUniversalTime();
            request.ModTimeFromSpecified = true;
            request.Pagination = new PaginationType();
            request.Pagination.EntriesPerPage = 200;
            request.Pagination.EntriesPerPageSpecified = true;
            request.Pagination.PageNumberSpecified = true;
            request.DisputeFilterType = DisputeFilterTypeCodeType.AllInvolvedClosedDisputes;
            request.DisputeFilterTypeSpecified = true;
            GetUserDisputesResponseType response;
            try
            {
                int currentPageNumber = 1;
                int totalPages = 0;
                string xml = string.Empty;
                do
                {
                    request.Pagination.PageNumber = currentPageNumber;
                    //Must have a count update before anycall
                    UpdateSessionCallCount();
                    response = service.GetUserDisputes(request);

                    totalPages = response.PaginationResult.TotalNumberOfPages;
                    currentPageNumber++;
                    xml += XmlUtility.SerializeToString(response, false) + "\r\n";
                }
                while (currentPageNumber <= totalPages);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                //Break  
                throw new Exception(ex.Message);
            }
        }//End GetUserDispute

        
    }
}
